package first.printABC;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintReent {
    private static Lock reentrantLock = new ReentrantLock();
    private static int state = 0;

    private static class Pa extends Thread {
        @Override
        public void run() {
            for (int i=0; i<10; ) {
                try {
                    reentrantLock.lock();
                    while (state % 3 == 0) {
                        System.out.print("A");
                        state++;
                        i++;
                    }
                } finally {
                    reentrantLock.unlock();
                }
            }
        }
    }

    private static class Pb extends Thread {
        @Override
        public void run() {
            for (int i=0; i<10; ) {
                try {
                    reentrantLock.lock();
                    while (state % 3 == 1) {
                        System.out.print("B");
                        state++;
                        i++;
                    }
                } finally {
                    reentrantLock.unlock();
                }
            }
        }
    }

    private static class Pc extends Thread {
        @Override
        public void run() {
            for (int i=0; i<10; ) {
                try {
                    reentrantLock.lock();
                    while (state % 3 == 2) {
                        System.out.print("C");
                        state++;
                        i++;
                    }
                } finally {
                    reentrantLock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Pa().start();
        new Pb().start();
        new Pc().start();
    }
}
